package com.fiberhome.app.network.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import io.reactivex.annotations.NonNull;

/**
 * Created by Deed on 2018/1/22.
 */

class UdpSender extends SocketSender {
    private final UdpBuilder builder;

    private DatagramSocket socket;
    /**
     *
     * @param builder UdpBuilder
     */
    UdpSender(@NonNull UdpBuilder builder) {
        super(builder);
        this.builder = builder;
    }

    @Override
    public void cancel() {
        if (socket != null) {
            socket.close();
        }
    }

    @Override
    protected String send() throws IOException {
        try {
            socket = new DatagramSocket();
            InetAddress host = InetAddress.getByName(builder.ipAddress);
            if (host != null) {
                if (builder.udpPacket == null) {
                    builder.udpPacket = new DefaultUdpPacket();
                }

                byte[] sendBuffer = builder.udpPacket.sendData(builder.sendData).getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, host, builder.port);
                socket.send(sendPacket);
                byte[] receiveBuffer = new byte[1024];

                DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
                socket.setSoTimeout(builder.timeOut);
                socket.receive(receivePacket);

                return builder.udpPacket.getResult(receivePacket);
            } else {
                throw new IOException("Invalid host : " + builder.ipAddress);
            }
        } finally {
            if (socket != null) {
                socket.close();
            }
        }

    }

}
